﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Web;
using System.Web.Configuration;
using System.Web.Security;
using System.Web.Services;
using System.Web.UI.WebControls;
using nplJobsBLL.Common;
using nplJobsBLL.ProcessEmployeer;
using nplJobsBLL.ProcessJobSeeker;
using nplJobsCommon.Employeer;
using nplJobsCommon.JobSeeker;
using Elmah;

public partial class NewUser : BasePage
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            LoadEmployeerType();
        }
    }

    /// <summary>
    ///This function loads city
    /// </summary>
    #region  LoadEmployeerType()
    public void LoadEmployeerType()
    {
        try
        {
            ProcessEmployeerType employeertype = new ProcessEmployeerType();
            employeertype.invoke();
            ddlCompanyType.DataSource = employeertype.EmployeerType;
            ddlCompanyType.DataTextField = "Type";
            ddlCompanyType.DataValueField = "ID";
            ddlCompanyType.DataBind();
        }
        catch (Exception exp)
        {
            throw new Exception(exp.Message.ToString());
        }
    }
    #endregion

    /// <summary>
    /// Is user exists
    /// </summary>
    /// <param name="username"></param>
    /// <returns></returns>
    #region UserExists
    private bool UserExists(string username)
    {
        if (System.Web.Security.Membership.GetUser(username) != null) { return true; }

        return false;
    }
    #endregion

    /// <summary>
    /// Employeer entry related events
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    #region cuwEmployeer events
    protected void cuwEmployeer_NextButtonClick(object sender, WizardNavigationEventArgs e)
    {
        e.Cancel = false;
    }

    protected void cuwJobSeeker_NextButtonClick(object sender, WizardNavigationEventArgs e)
    {
        e.Cancel = false;
    }
    
    #endregion

    [WebMethod]
    public static string SaveEmployeer(object parms)
    {
        string error = string.Empty;
        try
        {
            if (HttpContext.Current.Session["userInfo"] == null)
            {
                string txtEmployeerUserName = GetObject(parms, "txtEmployeerUserName").ToString();
                string txtEmployeerPassword = GetObject(parms, "txtEmployeerPassword").ToString();

                System.Web.Security.MembershipUser newUser = System.Web.Security.Membership.CreateUser(txtEmployeerUserName, txtEmployeerPassword);

                //update membership user (IsApproved = false) during employeer creation
                newUser.IsApproved = false;
                Membership.UpdateUser(newUser);

                Employeer employeer = new Employeer();
                employeer.CompanyName = GetObject(parms, "txtEmployeerCompanyName").ToString();
                employeer.EmployeerID = (Guid)newUser.ProviderUserKey;
                employeer.Email = txtEmployeerUserName;
                employeer.EmployeerTypeID = Convert.ToInt32(GetObject(parms, "ddlCompanyType").ToString());
                employeer.EmployeeRangeID = -1;
                employeer.LocationID = -1;
                employeer.IndustryTypeID = -1;
                employeer.City = -1;
                employeer.Password = txtEmployeerPassword;

                //User type : Employeer which is 2
                employeer.UserType = 2;

                EmployeerContactPerson ecp = new EmployeerContactPerson();
                ecp.EmployeerID = employeer.EmployeerID;
                ecp.FirstName = GetObject(parms, "txtEmployeerFirstName").ToString();
                ecp.LastName = GetObject(parms, "txtEmployeerLastName").ToString();
                ecp.ContactNumber = GetObject(parms, "txtEmployeerPhone").ToString();

                ProcessInserEmployeer employeerinsert = new ProcessInserEmployeer();
                employeerinsert.Employeer = employeer;
                employeer.EmployeerContactPerson = ecp;
                employeerinsert.invoke();

                SentEmailNotification(employeer.EmployeerID, GetObject(parms, "txtEmployeerFirstName").ToString(), true, txtEmployeerUserName, out error);

                HttpContext.Current.Session.Add("JobSeekerUser", false);
            }
            else
                error = "USER_LOGGEDIN";
        }
        catch (MembershipCreateUserException ex)
        {
            return GetErrorMessage(ex.StatusCode);
        }
        return error;
    }

    [WebMethod]
    public static string SaveJobSeeker(object parms)
    {
        string error = string.Empty;
        try
        {
            if (HttpContext.Current.Session["userInfo"] == null)
            {
                string txtJobSeekerUserName = GetObject(parms, "txtJobSeekerUserName").ToString();
                string txtJobSeekerPassword = GetObject(parms, "txtJobSeekerPassword").ToString();

                System.Web.Security.MembershipUser newUser = System.Web.Security.Membership.CreateUser(txtJobSeekerUserName, txtJobSeekerPassword);

                //update membership user (IsApproved = false) duing job seeker creation
                newUser.IsApproved = false;
                Membership.UpdateUser(newUser);

                JobSeeker jobSeeker = new JobSeeker();
                jobSeeker.JobSeekerID = (Guid)newUser.ProviderUserKey;
                jobSeeker.FirstName = GetObject(parms, "txtJobSeekerFirstName").ToString();
                jobSeeker.LastName = GetObject(parms, "txtJobSeekerLastName").ToString();
                jobSeeker.DOB = System.DateTime.Now;
                jobSeeker.Email = txtJobSeekerUserName;
                jobSeeker.NationalityID = 1;
                jobSeeker.PostalAddress = string.Empty;
                jobSeeker.GenderID = 1;
                jobSeeker.MobilePhone = string.Empty;
                jobSeeker.AboutMe = string.Empty;

                //User type : Jobseeker which is 1
                jobSeeker.UserType = 1;

                ProcessInsertJobSeeker insertJobSeeker = new ProcessInsertJobSeeker();
                insertJobSeeker.JobSeeker = jobSeeker;
                insertJobSeeker.invoke();
                var LastJobSeekerID = insertJobSeeker.LastJobSeekerID;

                SentEmailNotification(jobSeeker.JobSeekerID, GetObject(parms, "txtJobSeekerFirstName").ToString(), false, txtJobSeekerUserName, out error);

                HttpContext.Current.Session["JobSeekerUser"] = true;
            }
            else
                error = "USER_LOGGEDIN";
        }
        catch (MembershipCreateUserException ex)
        {
            return GetErrorMessage(ex.StatusCode);
        }
        return error;
    }

    [WebMethod]
    public static string CheckUserExists(string email)
    {
        string error = string.Empty;
        try
        {
            MembershipUser membershipUser = Membership.GetUser(email);
            if (membershipUser != null)
            {
                error = "Email already exists. Please enter a different email.";
            }
        }
        catch (MembershipCreateUserException ex)
        {
            return GetErrorMessage(ex.StatusCode);
        }
        return error;
    }

    [WebMethod]
    public static bool CheckLoggedIn()
    {
        bool flag = true;
        try
        {
            if (HttpContext.Current.Session["userInfo"] == null)
            {
                flag = false;
            }
        }
        catch (MembershipCreateUserException ex)
        {
            ErrorSignal.FromCurrentContext().Raise(ex);
        }
        return flag;
    }

    protected void btnJobSeekerSave_OnClick(object sender, EventArgs e)
    {

    }

    private static string GetErrorMessage(MembershipCreateStatus status)
    {
        string str = string.Empty;
        switch (status)
        {
            case MembershipCreateStatus.DuplicateUserName:
                str = "Email already exists. Please enter a different email.";
                break;
            case MembershipCreateStatus.DuplicateEmail:
                //"A username for that e-mail address already exists. Please enter a different e-mail address.";
                break;
            case MembershipCreateStatus.InvalidPassword:
                str = "The password provided is invalid. Please enter a valid password value.";
                break;
            case MembershipCreateStatus.InvalidEmail:
                //"The e-mail address provided is invalid. Please check the value and try again.";
                break;
            case MembershipCreateStatus.InvalidAnswer:
                //"The password retrieval answer provided is invalid. Please check the value and try again.";
                break;
            case MembershipCreateStatus.InvalidQuestion:
                //"The password retrieval question provided is invalid. Please check the value and try again.";
                break;
            case MembershipCreateStatus.InvalidUserName:
                str = "The user name provided is invalid. Please check the value and try again.";
                break;
            case MembershipCreateStatus.ProviderError:
                //"The authentication provider returned an error. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
                break;
            case MembershipCreateStatus.UserRejected:
                //"The user creation request has been canceled. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
                break;
            default:
                //"An unknown error occurred. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
                break;
        }
        return str;
    }

    private static object GetObject(object parms, string key)
    {
        Dictionary<string, object> parmsList = ((Dictionary<string, object>)(parms));
        object value;
        parmsList.TryGetValue(key, out value);
        return (value == null || string.IsNullOrEmpty(value.ToString())) ? DBNull.Value : value;
    }

    private static void SentEmailNotification(Guid newUserAccountId, string userName, bool userType, string toAddress, out string error)
    {
        error = string.Empty;
        try
        {
            string domainName = HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority) + HttpContext.Current.Request.ApplicationPath;
            string confirmationPage = "/EmailConfirmation.aspx?ID=" + newUserAccountId.ToString();
            string url = domainName + confirmationPage;

            var fromAddress = WebConfigurationManager.AppSettings["EMAIL_FROM_ADDRESS"];
            var fromPassword = WebConfigurationManager.AppSettings["EMAIL_FROM_PASSWORD"];
            var smtpAddress = WebConfigurationManager.AppSettings["SMTP_ADDRESS"];
            var smtPort = WebConfigurationManager.AppSettings["SMTP_PORT"];
            string subject = "Reg:nplJobs User Activation";

            string logo_link = "http://www.npljobs.com/Images/npljobs.jpg";

            string body =  string.Empty;
            if (userType) //Employeer
                body = GetMailBody().Replace("<%NPL_LOGO%>", logo_link).Replace("<%FIRST_NAME%>", userName).Replace("<%USER_TYPE%>", "Employeer").Replace("<%VerificationUrl%>", url);
            else //Job Seeker
                body = GetMailBody().Replace("<%NPL_LOGO%>", logo_link).Replace("<%FIRST_NAME%>", userName).Replace("<%USER_TYPE%>", "Job Seeker").Replace("<%VerificationUrl%>", url);

            System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage(fromAddress, toAddress, subject, body);
            mail.Bcc.Add("manobesh1982@gmail.com");
            mail.CC.Add("sjais10@gmail.com");
            mail.IsBodyHtml = true;

            System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient();
            smtp.Host = smtpAddress;
            smtp.Port = Convert.ToInt32(smtPort);
            smtp.UseDefaultCredentials = false;
            smtp.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
            smtp.Credentials = new System.Net.NetworkCredential(fromAddress, fromPassword);
            smtp.EnableSsl = false;
            smtp.Send(mail);
        }
        catch (Exception ex)
        {
            ErrorSignal.FromCurrentContext().Raise(ex);
        }
    }

    private static string GetMailBody()
    {
        string domainName = HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority) + HttpContext.Current.Request.ApplicationPath;
        StringBuilder sb = new StringBuilder();
        try
        {
            using (StreamReader sr = new StreamReader(HttpContext.Current.Server.MapPath("/Resources//mail.txt")))
            {
                String line = sr.ReadToEnd();
                sb.Append(line);
            }
        }
        catch (Exception ex)
        {
            ErrorSignal.FromCurrentContext().Raise(ex);

        }
        return sb.ToString();
    }
}